<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件
use app\common\model\Configs;

function pr($arrs, $exit = 1){
    echo '<pre>';
    print_r($arrs);
    echo '</pre>';
    if($exit) exit;
}

//接口返回格式定义
function apiReturn($data=[],$code=1,$msg='无消息',$empty = false){
    echo json_encode(['code'=>$code,'data'=>$data,'msg'=>$msg,'empty'=>$empty]);exit;
}


//获取请求信息
function getRequest($url = ''){
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_TIMEOUT, 500);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($curl, CURLOPT_URL, $url);

    $res = curl_exec($curl);
    curl_close($curl);

    return $res;
}

//模拟POST
function curlPost($url, $data,$showError=1){
    $ch = curl_init();
    $header = "Accept-Charset: utf-8";
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $tmpInfo = curl_exec($ch);
    $errorno=curl_errno($ch);
    if ($errorno) {
        return array('rt'=>false,'errorno'=>$errorno);
    }else{
        $js=json_decode($tmpInfo,1);
        if (intval($js['errcode']==0)){
            return array('rt'=>true,'errorno'=>0,'media_id'=>$js['media_id'],'msg_id'=>$js['msg_id']);
        }else {
            if ($showError){
                return '发生了Post错误：错误代码'.$js['errcode'].',微信返回错误信息：'.$js['errmsg'];
            }
        }
    }
}
/**
 * Created by PhpStorm.
 * User: 727568210@qq.com
 * Date: 2019-03-06
 * Notes:微信接口返回格式
 */
function WechatReturn($data){
    $res = ['state'=>false,'data'=>[],'msg'=>'接口错误'];
    if(!isJson($data)){
        $res['msg'] = '数据结构异常';
        return $res;
    }
    $data = json_decode($data,true);
    if(isset($data['errcode']) && $data['errcode']){
        $res['msg']='接口错误：'.$data['errmsg'];
        return $res;
    }
    $res['state'] = true;
    $res['data'] = $data;
    $res['msg'] = '';
    return $res;
}

/**
 * 判断字符串是否为 Json 格式
 *
 * @param  string     $data  Json 字符串
 * @param  bool       $assoc 是否返回关联数组。默认返回对象
 *
 * @return bool|array 成功返回转换后的对象或数组，失败返回 false
 */
function isJson($data = '', $assoc = false) {
    $data = json_decode($data, $assoc);
    if ($data && (is_object($data)) || (is_array($data) && !empty(current($data)))) {
        return $data;
    }
    return false;
}
function random($length = 16)
{
    $string = '';

    while (($len = strlen($string)) < $length) {
        $size = $length - $len;

#        $bytes = random_bytes($size);
        $bytes = mt_rand(1,$size);
        $string .= substr(str_replace(['/', '+', '='], '', base64_encode($bytes)), 0, $size);
    }

    return $string;
}

/**
 * Created by PhpStorm.
 * User: 727568210@qq.com
 * Date: 2019-03-14 10:38
 * Notes:接口分页数据格式定义
 */
function pageReturn($data){
    $empty = false;
    pr($data);
    if(!count($data['data']))$empty = true;
    apiReturn($data,1,'无消息',$empty);
}

/**
 *
 * 产生随机字符串，不长于32位
 * @param int $length
 * @return 产生的随机字符串
 */
function nonceStr($length = 32)
{
    $chars = "abcdefghijklmnopqrstuvwxyz0123456789";
    $str ="";
    for ( $i = 0; $i < $length; $i++ )  {
        $str .= substr($chars, mt_rand(0, strlen($chars)-1), 1);
    }
    return $str;
}

function getIP(){
    if(!empty($_SERVER["HTTP_CLIENT_IP"])){
        $cip = $_SERVER["HTTP_CLIENT_IP"];
    }
    elseif(!empty($_SERVER["HTTP_X_FORWARDED_FOR"])){
        $cip = $_SERVER["HTTP_X_FORWARDED_FOR"];
    }
    elseif(!empty($_SERVER["REMOTE_ADDR"])){
        $cip = $_SERVER["REMOTE_ADDR"];
    }
    else{
        $cip = "无法获取！";
    }
    return $cip;
}

function xmlToArray($xml)
{
    //禁止引用外部xml实体
    libxml_disable_entity_loader(true);
    $values = json_decode(json_encode(simplexml_load_string($xml, 'SimpleXMLElement', LIBXML_NOCDATA)), true);
    return $values;
}
function setLink($array){
    $url = url('/',[],'',true);
    if(isset($array->avatar) && $array->avatar){
        $array->avatar = $url.mb_strcut($array->avatar,1);
        return $array;
    }
    if(isset($array->img) && $array->img){
        $array->img = $url.mb_strcut($array->img,1);
        return $array;
    }
    if(isset($array->video) && $array->video){
        $array->video = $url.mb_strcut($array->video,1);
    }
    if(isset($array['img']) && $array['img']){
        $array['img'] = $url.mb_strcut($array['img'],1);
        return $array;
    }
    if(isset($array['avatar']) && $array['avatar'] && !(isset($array->avatar) && $array->avatar)){
        $array['avatar'] = $url.mb_strcut($array['avatar'],1);
        return $array;
    }
    if(isset($array['video']) && $array['video']){
        $array['video'] = $url.mb_strcut($array['video'],1);
        return $array;
    }
    return $array;
}
function setUrl($str){
    $url = url('/',[],'',true);
    return $url.mb_strcut($str,1);
}
function setImgLink($list){
    $url = url('/',[],'',true);
    if($list){
        foreach ($list as $k=>$v){
            if(isset($v->img) && $v->img){
                $v->img = $url.mb_strcut($v->img,1);

                if(isset($v->video) && $v->video){
                    $v->video = $url.mb_strcut($v->video,1);
                }
                continue;
            }
            if(isset($v->video) && $v->video){
                $v->video = $url.mb_strcut($v->video,1);
                continue;
            }
            if(isset($v['img']) && $v['img']){
                $list[$k]['img'] = $url.mb_strcut($v['img'],1);
                if(isset($v['video']) && $v['video']){
                    $list[$k]['video'] = $url.mb_strcut($v['video'],1);
                }
                continue;
            }
            if(isset($v['video']) && $v['video']){
                $list[$k]['video'] = $url.mb_strcut($v['video'],1);
            }
        }
    }
    return $list;
}
function urlImg ($str){
    $url = url('/',[],'',true);

    return $url.mb_strcut($str,1);
}
function replaceLink($str){
    $url = url('/',[],'',true);
    return '/'.str_replace($url,'',$str);

}
function getSetting($where){
    $setting = \app\api\model\Setting::where($where)->find();

    if($setting){
        return $setting['content'];
    }
    return null;

}

function companyPass($str){
    return md5($str.'tyjcompanyhueiaf*&T^*##^&*&Y!#YG&T&&');
}
function userPass($str){
    return md5($str);
}
function adminPass($str){
    return md5($str.'tyjadminH*^T&R%FGUJHDRFYT$');
}
function urlReplace($str){
    if(!$str){
        return '';
    }
    $url = url('/',[],'',true);
    $str = "".str_replace($url,'',$str);
    return  '/'.$str;
}
function imgsUrl($str){
    if(!$str){
        return [];
    }
    $arr = explode(',',$str);

    foreach ($arr as $ks => $vs){
        $arr[$ks] = urlImg($vs);
    }
    return  $arr;
}
function imgs2Str($str){
    if(!$str){
        return '';
    }
    $arr = json_decode($str);
    foreach ($arr as $k => $v){
        $arr[$k] = replaceLink($v);
    }
    $str = implode($arr,',');
    return  $str;
}
function jsonImgs2Str($str){
    if(!$str){
        return '';
    }
    $arr = explode(',',$str);
    foreach ($arr as $k => $v){
        $arr[$k] = replaceLink($v);
    }
    $str = implode($arr,',');
    return  $str;
}
function problemListSet($list){
    foreach ($list as $k => $v){
        if(!is_array($v)){
            $v = $v->toArray();
        }
        $v['imgs'] = imgsUrl($v['imgs']);
        $v['answerImgs'] = imgsUrl($v['answerImgs']);
        if(isset($v['user']) && $v['user']){
            $v['user'] = setLink($v['user']);
        }
        if(isset($v['teacher']) || $v['teacher']){
            $v['teacher'] = setLink($v['teacher']);
        }
        $list[$k]= $v;

    }
    return $list;

}
function sendTemlate($temId,$openid,$dataArr){
    $data = [];
    global $_W;
    $access_token = \app\api\model\Wechat::getAccessToken();
    $url = 'https://api.weixin.qq.com/cgi-bin/message/subscribe/send?access_token='.$access_token;

    $data['data'] = $dataArr;
    $data['access_token'] = $access_token;
    $data['touser'] = $openid;
    $data['template_id'] = $temId;
    $res = http_request($url,json_encode($data));
    return json_encode($res);

}

function http_request($url, $data = null)
{
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    curl_setopt($curl, CURLOPT_HTTPHEADER, array(
            'X-AjaxPro-Method:ShowList',
            'c',
            'Content-Length: ' . strlen($data)
        )
    );
    curl_setopt($curl, CURLOPT_POST, TRUE);
    curl_setopt($curl, CURLOPT_POSTFIELDS,$data);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
    $output = curl_exec($curl);
    curl_close($curl);
    return $output;
}
function pageLink($page){
    $page = $page->toArray();
    $page['data'] = setImgLink($page['data']);
    return $page;
}
function fenToYuan($num){
    return intval($num)/100;

}
function delFile ($file){
    $path = $file;
    $path = ROOT_PATH . 'public' . DS . $path;
    if (file_exists($path)) {
        unlink($path);//删除文件
    }
}
function getConfig(){
    return Configs::find(1)->toArray();
}

//字母（26）进制转10进制
function ABC2decimal($abc){
    $ten = 0;
    $len = strlen($abc);
    for($i=1;$i<=$len;$i++){
        $char = substr($abc,0-$i,1);//反向获取单个字符

        $int = ord($char);
        $ten += ($int-65)*pow(26,$i-1);
    }


    return $ten;
}

/**

 * 输出到浏览器(需要设置header头)

 * @param string $fileName 文件名

 * @param string $fileType 文件类型

 */

function excelBrowserExport($fileName, $fileType) {



    //文件名称校验

    if(!$fileName) {

        trigger_error('文件名不能为空', E_USER_ERROR);

    }



    //Excel文件类型校验

    $type = ['Excel2007', 'Xlsx', 'Excel5', 'xls'];

    if(!in_array($fileType, $type)) {

        trigger_error('未知文件类型', E_USER_ERROR);

    }



    if($fileType == 'Excel2007' || $fileType == 'Xlsx') {

        header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');

        header('Content-Disposition: attachment;filename="'.$fileName.'.xlsx"');

        header('Cache-Control: max-age=0');

    } else { //Excel5

        header('Content-Type: application/vnd.ms-excel');

        header('Content-Disposition: attachment;filename="'.$fileName.'.xls"');

        header('Cache-Control: max-age=0');

    }

}
